package tc.crase.db;

import java.awt.geom.Point2D;
import java.util.Iterator;
import java.util.Vector;

import tc.common.utility.Pair;
import tc.crase.sys.XdbRoot;

public class XattrGRP extends Xattr implements Iterable<XattrGIT> {

	//static private int maxid = 1;
	
	private int id;;
	
	public Vector<Pair<AttrId, XattrGIT>> items = new Vector<Pair<AttrId, XattrGIT>>();
	
	public Xobject parent;
	
	public XattrGRP(int id, Xobject parent) {
		super("group");

		if (id < 0) {
			this.id = parent.db.maxLinkId++; 
		}
		else {
			this.id = id;
			if ( parent.db.maxLinkId <= id ) parent.db.maxLinkId = id+1;   
		}
		
		this.parent = parent;
	}
	
	public void removeGID_(XattrGIT attr) {
		boolean remove = false;
		int index = 0;
		for (Pair<AttrId, XattrGIT> item : items) {
			if (item.second == null) {
				item.second = (XattrGIT)item.first.searchAttr(parent.getDb());
			}
			
			if (item.second != attr )
			{	index++;
				continue;
			}
			remove = true;
			break;
		}
		
		if (remove == false) return;
		
		items.remove(index);
	}
	
	public void createGXY (Xobject xobj, Point2D.Double xy) {
		String fileNameThis = "";
		String fileNameOpposite = "";

		if(xobj.getDb() != parent.getDb()) {
			fileNameThis = parent.getDb().fileName;
			fileNameOpposite = xobj.getDb().fileName;
		}
		
		int id = xobj.getDb().maxLinkId++;
		
		XattrGXY attrGXY = new XattrGXY(id, getId(), fileNameThis, xobj, xy);
		xobj.attrAdd(attrGXY);
		
		
		add(attrGXY.getId(), fileNameOpposite);
	}
	
	public void add(int id, String url) {
		items.add(new Pair<AttrId, XattrGIT>(new AttrId(id, url), null));
	}
	
	public int getId() {
		return id;
	}
	
	@Override
	public Iterator<XattrGIT> iterator() {
		return new IteratorGRP(this);
	}
	
	@Override
	public XattrGRP getAsGRP() { 
		return this;
	}
	
	@Override public String getValue() {
		String result = "";
		//for (Pair<Integer, XattrGIT> item : items) {
		for (XattrGIT attr : this) {
			if ("".equals(result) == false) result += ", ";
			if (attr == null) {
				result += "BR";
			}
			else {
				result += attr.getId();
			}
		}
		return result;
	}
	
	public class IteratorGRP implements Iterator<XattrGIT>{

		Iterator<Pair<AttrId, XattrGIT>> iterator;
		
		IteratorGRP(XattrGRP grp) {
			iterator = items.iterator();
		}
		
		@Override
		public boolean hasNext() {
			return iterator.hasNext();
		}

		@Override
		public XattrGIT next() {
			Pair<AttrId, XattrGIT> pair = iterator.next();
			if (pair.second == null) {
				//Xdb db;
				
				/*if (pair.first.getUrl().isEmpty()) {
					db = parent.getDb();
				}
				else {
					db = XdbRoot.xdbsys.searchDb(pair.first.getUrl());
				}*/
				
				pair.second = (XattrGIT)pair.first.searchAttr(parent.getDb());
			}
			return pair.second;
		}

		@Override
		public void remove() {
		}
	}
}
